package mall

import (
	"errors"
	"fmt"
	"github.com/jinzhu/copier"
	"gorm.io/gorm"
	"newbeemallStudyProject/global"
	"newbeemallStudyProject/model/common"
	"newbeemallStudyProject/model/mall"
	"newbeemallStudyProject/model/mall/request"
	"newbeemallStudyProject/model/mall/response"
	"newbeemallStudyProject/utils"
	"strconv"
	"strings"
	"time"
)

type MallUserService struct {
}

func (m *MallUserService) TestService() {
	fmt.Println("进入到service逻辑====")
}

func (m *MallUserService) QueryUserInfo(token string) (err error, resMall response.MallUserResponse) {
	fmt.Println("进入到service")
	var mallUserToken mall.MallUserToken
	err = global.GVA_DB.Where("token = ?", token).First(&mallUserToken).Error
	if err != nil {
		return errors.New("用户不存在"), resMall
	}
	var mallUser mall.MallUser
	err = global.GVA_DB.Where("user_id = ?", mallUserToken.UserId).First(&mallUser).Error
	if err != nil {
		return errors.New("用户信息获取失败"), resMall
	}
	copier.Copy(&resMall, &mallUser)
	return
}

func (m *MallUserService) RegisterUser(param request.RegisterUserParam) (err error) {
	//判断用户名是否有重复
	var user mall.MallUser
	_ = global.GVA_DB.Where("login_name = ?", param.LoginName).First(&user).Error
	if !errors.Is(global.GVA_DB.Where("login_name = ?", param.LoginName).First(&user).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在相同用户名")
	}
	return global.GVA_DB.Create(&mall.MallUser{
		LoginName:     param.LoginName,
		IntroduceSign: "畅想生活，春风与你同行",
		CreateTime:    common.JSONTime{Time: time.Now()},
		PasswordMd5:   utils.MD5V([]byte(param.Password)),
	}).Error
}

func (m *MallUserService) UserLogin(param request.UserLoginParam) (err error, user mall.MallUser, userToken mall.MallUserToken) {
	//判断账号密码是否正确
	if errors.Is(global.GVA_DB.Where("login_name = ? and password_md5 = ?", param.LoginName, param.PasswordMd5).First(&user).Error, gorm.ErrRecordNotFound) {
		return errors.New("未查询到该用户"), user, userToken
	}
	//判断该用户在token表里是否有数据
	err3 := global.GVA_DB.Where("user_id = ?", user.UserId).First(&userToken).Error
	//走到这说明账号密码通过验证
	//需进行token处理
	token := getNewToken(time.Now().UnixNano()/1e6, int(user.UserId))
	nowDate := time.Now()
	duration, _ := time.ParseDuration("48h")
	expireDate := nowDate.Add(duration)
	if err3 == nil {
		//表明该用户在token表中有数据 进行修改过期时间
		userToken.ExpireTime = expireDate
		userToken.UpdateTime = nowDate
		userToken.Token = token
		err1 := global.GVA_DB.Updates(userToken)
		if err1 != nil {
			return errors.New("修改数据失败"), user, userToken
		}
	} else {
		//该用户在token表中无数据  进行新增数据
		userToken.UserId = user.UserId
		userToken.Token = token
		userToken.ExpireTime = expireDate
		userToken.UpdateTime = nowDate
		err2 := global.GVA_DB.Create(&userToken).Error
		if err2 != nil {
			return errors.New("新增数据失败"), user, userToken
		}
	}
	return err, user, userToken
}

func getNewToken(timeInt int64, userId int) (token string) {
	var build strings.Builder
	build.WriteString(strconv.FormatInt(timeInt, 10))
	build.WriteString(strconv.Itoa(userId))
	build.WriteString(utils.GenValidateCode(6))
	return utils.MD5V([]byte(build.String()))
}

func (m *MallUserService) UserLayout(token string) (err error) {
	//判断该token是否存在
	var mallTokenUser mall.MallUserToken
	if errors.Is(global.GVA_DB.Where("token = ?", token).First(&mallTokenUser).Error, gorm.ErrRecordNotFound) {
		return errors.New("登出失败，请确认token")
	}
	//该token存在，进行删除token记录
	err1 := global.GVA_DB.Where("token = ?", token).Delete(&mallTokenUser).Error
	if err1 != nil {
		return errors.New("登出失败。。")
	}
	return
}

func (m *MallUserService) UserInfoUpdate(userUpdateParam request.UserUpdateParam, token string) (err error) {
	//判断该token是否存在
	var mallTokenUser mall.MallUserToken
	if errors.Is(global.GVA_DB.Where("token = ?", token).First(&mallTokenUser).Error, gorm.ErrRecordNotFound) {
		return errors.New("修改信息失败，请确认token")
	}
	//根据用户id查询该用户信息
	var userInfo mall.MallUser
	global.GVA_DB.Where("user_id = ?", mallTokenUser.UserId).First(&userInfo)
	if len(userUpdateParam.PasswordMd5) != 0 {
		userInfo.PasswordMd5 = utils.MD5V([]byte(userUpdateParam.PasswordMd5))
	}
	userInfo.IntroduceSign = userUpdateParam.IntroduceSign
	userInfo.NickName = userUpdateParam.NickName
	//进行数据修改
	err = global.GVA_DB.Where("user_id = ?", mallTokenUser.UserId).UpdateColumns(&userInfo).Error
	fields := []string{"nick_name", "introduce_sign"}
	// .select目前是强制更新，若不加select 当修改目标值为0或空时，gorm会认为不需要修改，与我们期望不相符
	err = global.GVA_DB.Select(fields).Where("user_id = ?", mallTokenUser.UserId).UpdateColumns(&userInfo).Error
	if err != nil {
		return errors.New("修改个人信息失败。。")
	}
	return
}
